<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者: 奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\user\controller;
use app\common\model\User;
use app\common\model\Message;
use app\common\model\FinanceRecharge;
class Codepay extends Base{

   public function initialize()
    {
	   parent::initialize();
 
    }
    protected function init(){


		if(empty($this->settings['pay']['codepay_status'])){
                        
			return $this->error('码支付充值未开启','user/finance/recharge');
		}
		if(empty($this->settings['pay']['codepay_id'])){
		   return $this->error('码支付ID没有配置','user/finance/recharge');
		}  
		if(empty($this->settings['pay']['codepay_key'])){
			return $this->error('通信密钥没有配置','user/finance/recharge');
		 }  	
		 if(empty($this->settings['pay']['codepay_type'])){
			return $this->error('码支付支付方式没有选择','user/finance/recharge');
		 }  
    }
// 处理支付
	public function pay(){
	       	$this->isLogin(); //支付必须登陆，初始化无需登陆
           $this->init(); //初始化配置
           
  
       $param = $this->request->param();	 

			   //验证
			   $rule =[    
				'money'=>'require|float|max:11',
					 
			   ];
			   $msg= [
				'money.require' =>'请输入充值金额',
				'money.float'   =>'请输入正确的金额格式',
				'money.max'     =>'充值金额超限',
			  ];
            $error = $this->checkSubmit($param,$rule,$msg);  //调用common 公共控制器中的 checkSubmit 方法
            if($error){
                return $this->error($error,'@user/finance/recharge');
			}  



            //构造请求
            $money  = sprintf("%.2f",$param['money']);
            $codepay_id  = $this->settings['pay']['codepay_id'];//这里改成码支付ID
            $codepay_key = $this->settings['pay']['codepay_key']; //这是您的通讯密钥
            $order_no = get_order_no(); //创建订单号
            $data =[];
            $data = array(
            "id"     => $codepay_id,//你的码支付ID
            "pay_id" => $order_no, //唯一标识 可以是用户ID,用户名,session_id(),订单ID,ip 付款后返回
            "type"   => $this->settings['pay']['codepay_type'],//1 码支付支付 2 QQ钱包 3 微信支付 
            "price"  => $money,//金额100元
            "param"  => "",//自定义参数'/user/alipay/returnUrl'
            "notify_url"=> request()->domain().url('@user/codepay/notify'),//通知地址
            "return_url"=> request()->domain().url('@user/codepay/return'),//跳转地址
            ); 

            //构造需要传递的参数

            ksort($data); //重新排序$data数组
            reset($data); //内部指针指向数组中的第一个元素

            $sign = ''; //初始化需要签名的字符为空
            $urls = ''; //初始化URL参数为空

            foreach ($data as $key => $val) { //遍历需要传递的参数
            if ($val == ''||$key == 'sign') continue; //跳过这些不参数签名
            if ($sign != '') { //后面追加&拼接URL
            $sign .= "&";
            $urls .= "&";
            }
            $sign .= "$key=$val"; //拼接为url参数形式
            $urls .= "$key=".urlencode($val); //拼接为url参数形式并URL编码参数值

            }

            $query = $urls.'&sign='.md5($sign.$codepay_key); //创建订单所需的参数
            $url = "http://api2.fateqq.com:52888/creat_order/?{$query}"; //支付页面

            //生成支付订单
            $insert_data['order_no'] = $order_no; //创建订单号
            $insert_data['amount']   = $money;
            $insert_data['uid']      = session('uid');
            $insert_data['username'] = session('username');
            $insert_data['create_time'] = time();
            $insert_data['bankname'] = '码支付';


            //判断订单id 是否存在
            if(cookie('codepay_order_id')){
            $map['id'] = cookie('codepay_order_id');
            $map['amount'] = $money;
            $map['status'] = 0;
            $financeRecharge  = model('FinanceRecharge')->infoData($map);
            $out_trade_no = $financeRecharge['order_no'];
            if(empty($financeRecharge)){
                $financeRecharge = model('FinanceRecharge')->addData($insert_data);
                $out_trade_no = $financeRecharge->order_no;
                cookie('codepay_order_id',$financeRecharge->id,24*3600);
            }
            }else{

                $financeRecharge = model('FinanceRecharge')->addData($insert_data);

                $out_trade_no = $financeRecharge->order_no;
                cookie('codepay_order_id',$financeRecharge->id,24*3600);
            
            }

            $this->redirect($url);//跳转到支付页面

  
	}

	public function return(){
		 if(!request()->isGet()){  return '非法请求';}
		       	$this->init();
            $param = $this->request->get();
         
            //业务处理
              $order_no = $param['pay_id']; //需要充值的ID 或订单号 或用户名    
              $price = $param['price'];//订单的原价
              $trade_no = !empty($param['pay_no'])?$param['pay_no']:''; //流水号
           
                $codepay_id  = $this->settings['pay']['codepay_id'];//这里改成码支付ID
                $codepay_key = $this->settings['pay']['codepay_key']; //这是您的通讯密钥
      
      
                ksort($param); //排序GET参数
                reset($param); //内部指针指向数组中的第一个元素
      
      
                $sign = '';//初始化
                foreach ($param as $key => $val) { //遍历GET参数
                    if ($val == '' || $key == 'sign' || $key == 'addon' || $key == 'controller' || $key == 'action') continue; //跳过这些不签名
                    if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
                    $sign .= "$key=$val"; //拼接为url参数形式
                }
           
      
                if (!$param['pay_no'] || md5($sign . $codepay_key) != $param['sign']) { //不合法的数据
                  exit('fail');  //返回失败 继续补单
                } else { //合法的数据
      
      
                  if(empty($trade_no)){
                    return $this->error("订单号不存在",'@user/finance/recharge');  
                  }

             
                  $where=[];
                  $where['order_no'] = $order_no;
                  $financeRecharge= model('FinanceRecharge')->infoData($where);
               
            
                  if(empty($financeRecharge)){
                    return  $this->error("该订单不存在",'@user/finance/recharge');  
                  } 
                  if($financeRecharge['status'] ==1){
                    return $this->success("已经充值成功",'@user/finance/recharge');  
                  }
              
                  if($financeRecharge['amount'] != $price){
                    return $this->error("返回金额错误",'@user/finance/recharge');  
                  }
                
                  //更新充值成功状态
                  $data=[];
                  $data['status']    = 1;
                  $data['pay_time']  = time();
                  $data['trade_no']  = $trade_no;
                  $where=[];
                  $where['order_no'] = $order_no;
                  $res = model('FinanceRecharge')->editData($data,$where);
                  //加钱
                  $user = new User();
                  $user->payin($financeRecharge['uid'],$financeRecharge['amount'],'码支付充值',"码支付");
            
                  // 发送消息
                  $url = '<a href="'.url('user/finance/rechargerecord')."?order_no=".$financeRecharge['order_no'].'">'.$financeRecharge['order_no'].'</a>';
                  $Message =  new Message();
                  $Message->send($financeRecharge['uid'],'码支付充值消息','充值订单号：'.$url.'，码支付充值成功');

                  $this->success('充值成功','@user/finance/recharge');
      
                   exit('success'); //返回成功 不要删除哦
      
                }
		

	}


/*
*********************************** 
* 支付成功 异步返回，线上使用才有效果
***********************************
*/	 
	public function notify(){
		if(!request()->isPost()){  return '非法请求';}

	  	//计算得出通知验证结果
		 $this->init();

          $post = $this->request->post();

              $codepay_id  = $this->settings['pay']['codepay_id'];//这里改成码支付ID
              $codepay_key = $this->settings['pay']['codepay_key']; //这是您的通讯密钥
  
              ksort($post); //排序post参数
              reset($post); //内部指针指向数组中的第一个元素
  
              $sign = '';//初始化
              foreach ($post AS $key => $val) { //遍历POST参数
                  if ($val == '' || $key == 'sign' ) continue; //跳过这些不签名
                  if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
                  $sign .= "$key=$val"; //拼接为url参数形式
              }
       
              if (!$post['pay_no'] || md5($sign . $codepay_key) != $post['sign']) { //不合法的数据
            
                  exit('fail');  //返回失败 继续补单
              } else { //合法的数据
  
                  //业务处理
                  $order_no = $post['pay_id']; //需要充值的ID 或订单号 或用户名
                  $price    = (float)$post['price']; //订单的原价
                  // $post    = $post['param']; //自定义参数
                  $trade_no = $post['pay_no']; //支付平台流水号
                  if(empty($order_no)){
                    // 平台订单号不存在
             
                      exit("fail");  
                  }
  
                  $where=[];
                  $where['order_no'] = $order_no;
                  $financeRecharge = model('FinanceRecharge')->infoData($where);
  
                  if(empty($financeRecharge)){
    
                      exit("fail");  
                  }
                  if($financeRecharge['status'] ==1){
                     exit('success'); //返回成功 不要删除哦
                  }

                  $total_money = $financeRecharge['amount']; //原价
                  $user_id     = $financeRecharge['uid'];
  
                  if($total_money != $price){
                    exit("fail");  
                  } 
              //更新充值成功状态
              $data['status']    = 1;
              $data['pay_time']  = time();
              $data['trade_no']  = $trade_no;
              $where['order_no'] = $order_no;
              $res = model('FinanceRecharge')->editData($data,$where);
              //加钱
              $User = new User;
              $User->payin($financeRecharge['uid'],$financeRecharge['amount'],'码支付充值',"码支付");
              // 发送消息
              $url = '<a href="'.url('user/finance/rechargerecord')."?order_no=".$financeRecharge['order_no'].'">'.$financeRecharge['order_no'].'</a>';
              $Message =  new Message();
              $Message->send($financeRecharge['uid'],'码支付充值消息','充值订单号：'.$url.'，码支付充值成功');
            
              exit('success'); //返回成功 不要删除哦
  
            } 

		

	}


}